创建型-原型模式

概念

Prototype Pattern:类似复印,根据原对象复印一个新对象,并根据需求对新对象进行微调。

使用

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
@interface Student : NSObject
@property (nonatomic, copy) NSString *name;
@property (nonatomic, copy) NSString *age;
@property (nonatomic, copy) NSString *class;
@property (nonatomic, copy) NSString *school;
@end

// 原对象
Student *lily = [Student alloc] init];
lily.name = @"lily";
lily.age = @"13";
lily.class = @"五年一班";
lily.school = @"实现学校";

// 复制原对象
Student *tom = [lily copy];
// 在原对象基础上微调
tom.name = @"tom";

比如js可以通过原型链,实现继承的五种方法

优点

  • 简化对象的创建过程

缺点

  • 对象包含的所有对象都需要配备一个克隆的方法,这就使得在对象层级比较多的情况下,代码量会很大,也更加复杂